package com.ruoyi.common.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.MinioException;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName MinIOFileUploader
 * @Description: MinIO文件上传器
 * @Author cjc
 * @Date 2020/6/4
 * @Version V1.0
 **/

public class MinIoFileUploader {

    public static String fileUpload(String fileName,  MultipartFile file) throws IOException, InvalidKeyException {
        try {
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getInputStream().available(), -1);
            // Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
            MinioClient minioClient = new MinioClient("http://121.199.76.161:9000", "minioadmin", "minioadmin");
            // Check if the bucket already exists.
            boolean isExist =
                    minioClient.bucketExists("shop");
            if(isExist) {
                System.out.println("Bucket already exists.");
            } else {
                minioClient.makeBucket("shop");
            }
            InputStream inputStream = file.getInputStream();
            file.getContentType();
            putObjectOptions.setContentType( file.getContentType());
            minioClient.putObject("shop",fileName, inputStream, putObjectOptions);
            String shop = minioClient.getObjectUrl("shop", fileName);
            inputStream.close();
            return shop;

        } catch(MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
